/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

// http://mxr.mozilla.org/firefox/source/toolkit/content/editMenuOverlay.js
function goUpdateEntryCommands()
{
    for each (var command in EntryController.prototype.commands)
        goUpdateCommand("cmd_" + command);
}


// nsIController
function EntryController()
{
    // empty
}

EntryController.prototype =
{
    commands: "editAccesskey addFolder addOpenPrefs addRecent addSaveAs addSeparator editEntry moveEntriesDown moveEntriesUp removeEntries toggleMenu".split(" "),
    
    get commandSet()
    {
        var prototype = EntryController.prototype;
        var commandSet = new Set(prototype.commands);
        return lazyInit(prototype, "commandSet", commandSet);
    },
    
    get type()     { return prefwindow.type; },
    get enabled()  { return prefwindow.enabled; },
    get treeView() { return prefwindow.treeView; },
    
    isCommandEnabled: function(command)
    {
        if (! (this.type && this.enabled))
            return false;
        
        var treeView = this.treeView;
        var selection = treeView.selection;
        
        switch (command)
        {
            case "cmd_editAccesskey":
            case "cmd_addFolder":
            case "cmd_addOpenPrefs":
            case "cmd_addRecent": 
            case "cmd_addSaveAs":
            case "cmd_addSeparator":
                return true;
                
            case "cmd_editEntry":
                return ((selection.count == 1) && (["folder", "item"].indexOf(treeView.selectedEntry.type) != -1));
                
            case "cmd_moveEntriesDown":
                var indexes = treeView.selectedIndexes;
                return ((selection.getRangeCount() == 1) && (indexes[indexes.length - 1] != (treeView.rowCount - 1)));
                
            case "cmd_moveEntriesUp":
                var indexes = treeView.selectedIndexes;
                return ((selection.getRangeCount() == 1) && (indexes[0] != 0));
                
            case "cmd_removeEntries":
                return (selection.count > 0);
                
            case "cmd_toggleMenu":
                return ((selection.count == 1) && (treeView.selectedEntry.type == "folder"));
                
            default:
                throw new Error("invalid command: " + command);
        }
    },
    
    supportsCommand: function(command)
    {
        // strip "cmd_"
        command = command.substr(4);
        return (command in this.commandSet);
    },
    
    doCommand: function(command)
    {
        if (this.isCommandEnabled(command))
            this[command]();
    },
    
    onEvent: function(eventName) { /* empty */ },
    
    cmd_editAccesskey: function()
    {
        let element = document.getElementById("btn_" + this.type + "_accesskey");
        let value = this._openAccesskeyDialog(element.value);
        if (value === null)
            return;
        
        element.value = (value ? value.charAt(0) : "");
        
        // dispatch change event so that the <preference> is updated
        let event = document.createEvent("Event");
        event.initEvent("change", true, true);
        element.dispatchEvent(event);
    },
    
    cmd_addFolder: function()
    {
        var entry = {label: "", path: "", menu: true};
        var entry = this._openFolderDialog("add", entry);
        if (entry)
            this._addEntry(entry);
    },
    
    cmd_addOpenPrefs: function()
    {
        this._addEntry(savefileto.getOpenPrefsCommandEntry(this.type));
    },
    
    cmd_addRecent: function()
    {
        this._addEntry(recentEntry);
    },
    
    cmd_addSaveAs: function()
    {
        this._addEntry(savefileto.getSaveAsCommandEntry(this.type));
    },
    
    cmd_addSeparator: function()
    {
        this._addEntry(separatorEntry);
    },
    
    cmd_editEntry: function()
    {
        var index = this.treeView.selectedIndex;
        var entry = this.treeView.selectedEntry;
        
        entry = this._editEntry(entry);
        if (entry)
            this.treeView.setEntry(index, entry);
    },
    
    cmd_removeEntries: function()
    {
        if (prefwindow.prefs.getBoolPref("confirmRemove"))
        {
            var title = prefwindow._("remove.title");
            var message = prefwindow._("remove.message");
            var checkLabel = prefwindow._("remove.check");
            var check = {value: false};
            var result = Services.prompt.confirmCheck(window, title, message, checkLabel, check);
            
            if (! result)
                return;
            
            prefwindow.prefs.setBoolPref("confirmRemove", (! check.value));
        }
        
        var indexes = this.treeView.selectedIndexes;
        this.treeView.removeEntries(indexes);
    },
    
    cmd_toggleMenu: function()
    {
        var index = this.treeView.selectedIndex;
        this.treeView.toggleMenu(index);
    },
    
    cmd_moveEntriesDown: function()
    {
        this._moveEntriesBy(1);
    },
    
    cmd_moveEntriesUp: function()
    {
        this._moveEntriesBy(-1);
    },
    
    _addEntry: function(entry)
    {
        var selection = this.treeView.selection;
        
        var index = this.treeView.currentIndex;
        if (index == undefined)
            index = this.treeView.selectedIndex;
        if (index == -1)
            index = this.treeView.rowCount;
        
        this.treeView.addEntries(index, [entry], true);
    },
    
    _editEntry: function(entry)
    {
        switch (entry.type)
        {
            case "folder": return this._openFolderDialog("edit", entry);
            case "item":   return this._openItemEditDialog(entry);
            default:       return null;
        }
    },
    
    _moveEntriesBy: function(delta)
    {
        var indexes = this.treeView.selectedIndexes;
        this.treeView.moveEntriesBy(indexes, delta);
    },
    
    _openAccesskeyDialog: function(value)
    {
        let title = prefwindow._("edit.accesskey.title");
        let message = prefwindow._("edit.accesskey." + this.type + ".message")
        let input = {value: value};
        let result = Services.prompt.prompt(window, title, message, input, null, {});
        return (result ? input.value.trim() : null);
    },
    
    _openFolderDialog: function(title, entry)
    {
        var args = {title: title, label: entry.label, path: entry.path, menu: entry.menu};
        var params = {args: args, result: null};
        document.documentElement.openSubDialog("chrome://savefileto/content/prefwindow/folder.xul", null, params);
        
        if (params.result)
            params.result.type = "folder";
        
        return params.result;
    },
    
    _openItemEditDialog: function(entry)
    {
        let title = prefwindow._("edit.item.title");
        let message = prefwindow._("edit.item.message")
        let input = {value: entry.label};
        let result = Services.prompt.prompt(window, title, message, input, null, {});
        
        if (result && (input.value.trim().length > 0))
        {
            entry.label = input.value.trim();
            return entry;
        }
        else
            return null;
    },
}
